package com.iory.db;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.iory.tianwangterminator.TianwangConst;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

public class TianwangSqliteHelper extends SQLiteOpenHelper {
	//The table and column name
	public static final String CREATE_TABLE_CAMERA = "create table cameraList ("
		+ "_id integer primary key autoincrement, "
		+ "_name text , "
		+ "_rtsp text , " 
		+ "_province text , "
		+ "_city text , " 
		+ "_free text default '1', "
		+ "_canuse text default '1', " 
		+ "_extflag text default '1', "
		+ "_extflagtwo text default '1'" 
		+ ");";
	public static final String CREATE_TABLE_TV = "create table tvList ("
		+ "_id integer primary key autoincrement, "
		+ "_name text , "
		+ "_rtsp text , " 
		+ "_free text default '1', "
		+ "_canuse text default '1', " 
		+ "_extflag text default '1', "
		+ "_extflagtwo text default '1'" 
		+ ");";
	//database column index
	public static final int COLUMN_ID		= 1;
	public static final int COLUMN_NAME	= 2;
	public static final int COLUMN_RTSP		= 3;
	public static final int COLUMN_PROVINCE		= 4;
	public static final int COLUMN_CITY		= 5;
	public static final int COLUMN_FREE	= 6;
	public static final int COLUMN_CANUSE		= 7;
	public static final int COLUMN_EXTFLAG		= 8;
	public static final int COLUMN_EXTFLAGTWO		= 9;
	public static String TABLE_CAMERA = "cameraList";
	public static String TABLE_TV = "tvList";
	
	private static String DB_PATH = "/data/data/com.iory.tianwangterminator/databases/";
	private static String DB_NAME = "tianwang.db";
	private static String DB_FILE_0 = "tianwang.db0";
	private static String DB_FILE_1 = "tianwang.db1";
	
	private SQLiteDatabase myDataBase; 
	private Context myContext;
	
	/**
	 * @param context 
	 * @param context
	 * @param name
	 * @param factory
	 * @param version
	 */
	public TianwangSqliteHelper(Context context) {
		super(context, DB_NAME, null, 1);
		myContext = context;
	}

	
    /*private static final TianwangSqliteHelper single = new TianwangSqliteHelper();
	
	public static TianwangSqliteHelper getInstance() {
        return single;
    }*/
	/* (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	/**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
			// do nothing - database already exist
		} else {
			createCameraTable();
			//create historylist table
			createTvTable();			
			
			/*// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			SQLiteDatabase db = this.getReadableDatabase();
			try {
				copyDataBase();
				db.close();
				myDataBase = this.getWritableDatabase();			
//				//create favoritelist table
//				createCameraTable();
//				//create historylist table
//				createTvTable();				
				
			} catch (IOException e) {
				throw new Error("Error copying database");
			}*/
		}
	}
	
	/**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
	private boolean checkDataBase() {
		FileInputStream fls = null;
		String myPath = DB_PATH + DB_NAME;
		try {
			
			fls = new FileInputStream(myPath);
		} catch (FileNotFoundException e) {
			// database does't exist yet.
			Log.i("SQL", "Database is NOT exist!");
		}
		return fls != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {
		Log.i("SQL", "copyDatabase");
		// Open your local db as the input stream
		InputStream myInput = TianwangConst.getInstanceContext().getAssets().open(DB_NAME);
		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;
		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);
		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		myInput.close();
		// Close the streams
		myOutput.flush();
		myOutput.close();
	}

	public SQLiteDatabase openDataBase() throws SQLException {
		// Open the database
		if(myDataBase == null)
		{
			myDataBase = this.getWritableDatabase();
		}
		return myDataBase;
	}
	
	
	public Cursor queryDataBase(String sql) throws SQLException {
		Cursor result = myDataBase.rawQuery(sql, null);
		return result;
	}

	
	/**
	 * since getting the data of tab
	 */
	public Cursor query(String tabName) 
	{  
		if(myDataBase == null)
		{
			myDataBase = getWritableDatabase();  
		}
        Cursor c = myDataBase.query(tabName, null, null, null, null, null, null);  
        return c;  
	} 
	
    /**
     * Create a new Tab for Favorite list
     */
    public void createCameraTable()
    {
    	if(myDataBase == null)
    	{
    		myDataBase = this.getWritableDatabase();
    	}
        try 
        {
        	myDataBase.execSQL(CREATE_TABLE_CAMERA);
        } 
        catch (SQLException e) 
        {
            Log.i("err", "create cameralist table failed");
        }
    }
    
    /**
     * Create a new Tab for History list
     */
    public void createTvTable()
    {
    	if(myDataBase == null)
    	{
    		myDataBase = this.getWritableDatabase();
    	}
        try 
        {
        	myDataBase.execSQL(CREATE_TABLE_TV);
        }
        catch (SQLException e) 
        {
            Log.i("err", "create tvList table failed");
        }
    }
    
    /**
     * insert data to tab
     */
    public void insertData(String tabName, String categoryName, String titleName, String value)
    {
    	
    	if(myDataBase == null)
    	{
    		myDataBase = this.getWritableDatabase();
    	}
    	
    	ContentValues contentValue = new ContentValues();
    	contentValue.put("category", categoryName);
    	contentValue.put("name", titleName);
    	contentValue.put("icon", value);
    	myDataBase.insert(tabName, "null", contentValue);
    	
    }
    /**
     * delete data from tab
     */
    public void deleteRecord(String tabName, int  index)
    {
    	if(myDataBase == null)
    	{
    		myDataBase = this.getWritableDatabase();
    	}
    	myDataBase.delete(tabName, "_id=?", new String[] {String.valueOf(index)});
    }

    /**
     * clean the tab	
     */
	public void cleanTab(String tabName)
	{
    	if(myDataBase == null)
    	{
    		myDataBase = this.getWritableDatabase();
    	}
    	myDataBase.delete(tabName, "_id>?", new String[] {"-1"});
	}
    
    
	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}
}
